﻿
Option Explicit On
Option Strict Off

'*******************************************************************
' Program: Data Center Visio Rack Tool
' Author: Albert E Edlund
' Date:
'
' Purpose:
' ItemsSource="{Binding Data, ElementName=source}" 
' CurrentItem="{Binding SelectedItem, ElementName=_dataGrid}"
'
'*******************************************************************

Imports System
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Controls.DomainDataSource
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports System.Windows.Navigation '
Imports System.Windows.Browser
Imports System.Windows.Data
Imports System.Windows.Controls.DataForm
Imports System.IO
Imports System.ServiceModel.DomainServices.Client
Imports Microsoft.VisualBasic
Imports System.Diagnostics.CodeAnalysis



Imports DC_RackSLDE.Web
Imports DC_RackSLDE.LoginUI
Imports System.Text



Partial Public Class vwtblAttrApplication
    Inherits Page

#Region " Properties and Declarations "




#End Region

#Region " Constructor "

    '
    '
    '
    Public Sub New()
        InitializeComponent()

    End Sub

#End Region

#Region " Form Events "

    'Executes when the user navigates to this page.
    Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)

    End Sub

    '
    ' save the data as excel xml 
    ' TODO: excelTemplate.txt column headers use the example code 
    ' TODO: records saved are just for the current pagesize the grid shows the datapager size
    '
    Private Sub btnExport_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)

        Try

            Throw New NotImplementedException

            'Dim context = TryCast(dds.DomainContext, DC_RackDataDomainContext)

            '' requires the "excelTemplate.txt" file to be loaded....
            '' we save it in the "dc_rack.other" directory
            'Dim strTemplate = "excelTemplate.txt"
            'Dim s = Application.GetResourceStream(New Uri(strTemplate, UriKind.Relative))

            'Dim dialog = New SaveFileDialog()

            'dialog.DefaultExt = "*.xml"
            'dialog.Filter = "Excel Xml (*.xml)|*.xml|All files (*.*)|*.*"

            'If dialog.ShowDialog() = False Then
            '    Exit Sub
            'End If

            'Using sw = New StreamWriter(dialog.OpenFile())
            '    Dim sr = New StreamReader(s.Stream)
            '    While Not sr.EndOfStream
            '        Dim line = sr.ReadLine()
            '        If line = "***" Then
            '            Exit While
            '        End If
            '        sw.WriteLine(line)
            '    End While

            '
            ' write out the data to the xml file
            '
            'For Each prod In context.tblProductDatas
            '    sw.WriteLine("<Row>")
            '    sw.WriteLine("<Cell><Data ss:Type=""String"">{0}</Data></Cell>", prod.prodVendor.ToString)
            '    sw.WriteLine("<Cell><Data ss:Type=""String"">{0}</Data></Cell>", prod.prodProduct.ToString)
            '    sw.WriteLine("<Cell><Data ss:Type=""String"">{0}</Data></Cell>", prod.prodModel.ToString)
            '    sw.WriteLine("<Cell><Data ss:Type=""String"">{0}</Data></Cell>", prod.prodPartNr.ToString)
            '    sw.WriteLine("</Row>")
            'Next


            'While Not sr.EndOfStream
            '    sw.WriteLine(sr.ReadLine())
            'End While

            'End Using

        Catch ex As Exception

            ErrorWindow.CreateNew(ex, StackTracePolicy.Always)


        End Try



    End Sub

    '
    ' make sure the selected item is now the current item
    '
    Private Sub _dataGrid_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)

        If e.AddedItems.Count = 1 Then
            _dataForm.CurrentItem = e.AddedItems(0)
        End If

    End Sub

    '
    ' submit the changes made in the local domaincontext to the database
    '
    Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        'TODO: Add event handler implementation here.

        If WebContext.Current.User IsNot Nothing AndAlso WebContext.Current.User.IsAuthenticated Then
            dds.SubmitChanges()
        Else
            AddHandler WebContext.Current.Authentication.LoggedIn, AddressOf Current_LoginCompleted
            Dim newWindow As New LoginRegistrationWindow
            newWindow.Show()
        End If

    End Sub

    '
    ' when the login completes submit any pending changes
    '
    Private Sub Current_LoginCompleted(ByVal sender As Object, ByVal e As AuthenticationEventArgs)
        If blnDelete = True Then
            Dim context = TryCast(dds.DomainContext, tblAttrApplication_DCRackDomainContext)
            ' remove the current selected item from the datagrid
            context.tblAttrApplications.Remove(_dataGrid.SelectedItem)
            blnDelete = False
        End If
        dds.SubmitChanges()
        RemoveHandler WebContext.Current.Authentication.LoggedIn, AddressOf Current_LoginCompleted
    End Sub

    '
    '
    '
    Private blnDelete As Boolean
    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try

            Dim delConn As tblAttrApplication = _dataForm.CurrentItem
            If delConn IsNot Nothing Then
                blnDelete = True
                '
                ' has to be authenticated
                '
                If WebContext.Current.User IsNot Nothing AndAlso WebContext.Current.User.IsAuthenticated Then
                    Dim context = TryCast(dds.DomainContext, tblAttrApplication_DCRackDomainContext)
                    ' remove the current selected item from the datagrid
                    context.tblAttrApplications.Remove(_dataGrid.SelectedItem)
                    ' submit the changes
                    dds.SubmitChanges()
                    blnDelete = False
                Else
                    ' add a handler 
                    AddHandler WebContext.Current.Authentication.LoggedIn, AddressOf Current_LoginCompleted
                    Dim newWindow As New LoginRegistrationWindow
                    newWindow.Show()
                End If
            Else

                ' clear the tablefilter text if anything is there
                'If Me.tableFilterBox.Text <> "" Then
                '    Me.tableFilterBox.Text = ""
                'End If

            End If

        Catch ex As Exception
            ErrorWindow.CreateNew(ex, StackTracePolicy.Always)

        End Try

    End Sub

    '
    ' open the create attribute child window
    '
    Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

        If WebContext.Current.User IsNot Nothing AndAlso WebContext.Current.User.IsAuthenticated Then
            Dim newAttrAppForm As addtblAttrApplication = New addtblAttrApplication
            ' add a handler for when the window closes
            AddHandler newAttrAppForm.Closed, AddressOf AttrAppForm_Closed
            ' show the child window
            newAttrAppForm.Show()
        Else
            ' add a handler 
            AddHandler WebContext.Current.Authentication.LoggedIn, AddressOf Current_LoginCompleted
            Dim newWindow As New LoginRegistrationWindow
            newWindow.Show()
        End If

    End Sub

    '
    ' event handler for create changes childwindow 
    '
    Private Sub AttrAppForm_Closed(ByVal sender As Object, ByVal e As EventArgs)

        Try

            Dim newAttrAppForm As addtblAttrApplication = sender
            If Not newAttrAppForm._dataForm Is Nothing Then

                ' get the current item from the dataform
                Dim newAttrApp As tblAttrApplication = newAttrAppForm._dataForm.CurrentItem
                ' do not try to submit with known errors
                If newAttrApp.ValidationErrors.Count = 0 Then
                    ' get the domaincontext
                    Dim context = TryCast(dds.DomainContext, tblAttrApplication_DCRackDomainContext)
                    Dim strUser As String = WebContext.Current.User.ToString
                    newAttrApp.appLastEdit = strUser
                    newAttrApp.appLastUpdate = Today
                    ' add the new row to the entity set
                    context.tblAttrApplications.Add(newAttrApp)

                    ' submit the changes to the database
                    'dds.SubmitChanges()

                Else
                    'give the user a list of the errors
                    Dim colResults As System.Collections.Generic.List(Of System.ComponentModel.DataAnnotations.ValidationResult)
                    colResults = newAttrApp.ValidationErrors.ToList
                    Dim sbResults As StringBuilder = New StringBuilder
                    sbResults.AppendLine("Data Validation Errors")
                    For Each strResult In colResults
                        sbResults.AppendLine(strResult.ToString)
                    Next
                    ErrorWindow.CreateNew(sbResults.ToString, StackTracePolicy.Always)

                End If
            End If


        Catch ex As Exception
            ErrorWindow.CreateNew(ex, StackTracePolicy.Always)

        End Try

    End Sub

    '
    '
    '
    Private Sub dds_LoadingData(ByVal sender As System.Object, ByVal e As System.Windows.Controls.LoadingDataEventArgs)

        dds.DomainContext.EntityContainer.Clear()
        dds.Clear()
        e.LoadBehavior = LoadBehavior.RefreshCurrent

    End Sub

    '
    ' remember this is skeleton code and data validation errors during submission can
    ' occur, which will trash this
    '
    Private Sub dds_SubmittedChanges(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SubmittedChangesEventArgs)



        Dim strMessage As String = "no error message"

        Try

            If e.Error IsNot Nothing Then
                strMessage = e.Error.Message.ToString
                ErrorWindow.CreateNew(strMessage, StackTracePolicy.Always)
                ' if there is an error get out now........
                Exit Sub
            End If

            ' if no entities reported then get out
            If e.ChangeSet.AddedEntities.Count = 0 _
                And e.ChangeSet.ModifiedEntities.Count = 0 _
                And e.ChangeSet.RemovedEntities.Count = 0 Then
                'nothing happened get out 
                Exit Sub
            End If

            ' movetonextpage will force a (re)load - needed because wcf/ria does not have a refresh function
            dds.DataView.MoveToNextPage()
            ' selecting index 0 appears to be an issue, use 1 instead
            _dataGrid.SelectedIndex = 1
            _dataGrid.SelectedItem = dds.DataView.CurrentItem
            _dataForm.CurrentItem = _dataGrid.SelectedItem


        Catch ioe As InvalidOperationException
            ErrorWindow.CreateNew(ioe.Message.ToString, StackTracePolicy.Always)
        Catch de As DomainServices.Client.DomainException
            ErrorWindow.CreateNew(de.Message.ToString, StackTracePolicy.Always)
        Catch doe As DomainServices.Client.DomainOperationException
            ErrorWindow.CreateNew(doe.Message.ToString, StackTracePolicy.Always)
        Catch ex As System.Exception
            ErrorWindow.CreateNew(ex, StackTracePolicy.Always)
        End Try

        System.GC.Collect()
        System.GC.Collect()

    End Sub


#End Region



End Class
